//
//  YHPUserAccount.swift
//  SinaSwift
//
//  Created by Yan on 16/3/10.
//  Copyright © 2016年 baidu. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
/*
    字典转模型
    保存用户信息
    向外面提供一个获取数据的方法
*/

let  UserInfoKey = "swallowYan.com"

// 模型操作
class YHPUserAccount: NSObject {
    
    static let shareAccount = YHPUserAccount()
    
    var  access_token: String?
    //用于调用access_token，接口获取授权后的access token。
    // access_token的生命周期，单位是秒数。
    // private var  remind_in  :  String?
    //	access_token的生命周期（该参数即将废弃，开发者请使用expires_in）。
    //	当前授权用户的UID。
    var  uid: String?
    //用户名字
    var name: String?
    //用户头像
    var avatar_large: String? {
        //set 方法耗内存
        didSet {
            headImageURL = NSURL(string: avatar_large ?? "")
        }
    }
    var headImageURL : NSURL?
    var expires_date : NSDate?
    
    var expires_in: NSTimeInterval = 0 {
        didSet {
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    var userLogin : Bool {
        return access_token != nil
    }
    
    override init() {
        super.init()
        self.loadUserInfo()
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
}


// 扩展 业务逻辑  获取数据
extension YHPUserAccount {
 
    //MARK: 保存数据
    func saveUserInfo (dict:[String : AnyObject]) {
        
        //给当前对象KVC设置初始值 - 未登录状态 -》 登录状态
        self.setValuesForKeysWithDictionary(dict)
        
        //保存当前对象的所有属性 已字典的形式
        let userDefaults = NSUserDefaults.standardUserDefaults()
        //获取当前对象的字典信息

        let keys = ["expires_in","access_token","uid","name","avatar_large","expires_date"]
        let accountDict = self.dictionaryWithValuesForKeys(keys)
        print(accountDict)
        //将用户信息保存到沙盒中
        userDefaults.setObject(accountDict, forKey: UserInfoKey)
    
        // 同步
        userDefaults.synchronize()
        
        print(NSHomeDirectory())
        
    }
    
    func loadUserInfo () {
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(UserInfoKey) as? [String: AnyObject] else {
            return
        }
        self.setValuesForKeysWithDictionary(dict)
        if self.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            print("token正常")
            print(dict["access_token"])
        } else {
            print("token过期")
            self.access_token = nil
        }
        
        
    }
    
    
}
    
    extension YHPUserAccount {
        func loadAccountToken (code:String,finish:(isSuccess:Bool)->()){
            let urlString = "https://api.weibo.com/oauth2/access_token"
            let parameters = ["client_id": client_id,"client_secret": client_secret,"grant_type": grant_type,"code": code,"redirect_uri": redirect_uri]
            let AFN = AFHTTPSessionManager()
            AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
            AFN.POST(urlString, parameters: parameters, progress: nil
                , success: { (_, result) -> Void in
                    
                    guard let dict = result as? [String: AnyObject] else {
                        SVProgressHUD.showErrorWithStatus("数据格式错误")
                        finish(isSuccess: false)
                        return
                    }
                   
                    self.loadUserInfo(dict,finish: finish)
                }) { (_, error) -> Void in
                    print(error)
                    finish(isSuccess: false)
            }
            
        }
        
        /*
        access_token	true	string	采用OAuth授权方式为必填参数，OAuth授权后获得。
        uid
        */
        
        func loadUserInfo(dict:[String : AnyObject],finish:(isSuccess:Bool)->()) {
            let access_token = dict["access_token"] as! String
            let uid = dict["uid"] as! String
            let dictUser = ["access_token" : access_token,"uid": uid]
            let AFN = AFHTTPSessionManager()
            AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
            AFN.GET(URLUser, parameters: dictUser, progress: nil, success: { (_, result) -> Void in
                //类型转换
                guard var userInfoDict = result as? [String: AnyObject] else {
                    return
                }
                //KVC赋值 合并字典 爸传过来的dict 和userInfoDict合并
                for (k,v) in dict {
                    userInfoDict[k] = v
                }
                YHPUserAccount.shareAccount.saveUserInfo(userInfoDict)
                
                finish(isSuccess: true)
                //偏好设置保存数据 不能为空值否则程序崩溃 使用字典转模型
                //NSUserDefaults.standardUserDefaults().setValue(userInfoDict, forKey: "swallowYan.cn")
                }) { (_, error) -> Void in
                    print(error)
                    finish(isSuccess: false)
            }
        }

    }
    

